import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.TextConstruct;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;

public class YouTubeFeedRetriever {
	private final String YOUTUBE_FEEDS_URL = "http://gdata.youtube.com/feeds/api/videos";
	private final String YOUTUBE_EMBEDDED_URL = "http://youtube.com/v/";
	private final String CLIENT_ID = "MusicLounge";
	private final int TIMEOUT = 2000;
	private final int MAX_RESULTS = 5;
	
	private YouTubeService service;
	
	public YouTubeFeedRetriever() {
		service = new YouTubeService(CLIENT_ID);
		service.setConnectTimeout(TIMEOUT);
	}
	
	private static List<YouTubeFeedEntry> convertToFeedEntries(List<VideoEntry> videoEntryList) {
		List<YouTubeFeedEntry> entryList = new ArrayList<YouTubeFeedEntry>();
		
		for (VideoEntry video : videoEntryList) {
			entryList.add(new YouTubeFeedEntry(video));
		}
		
		return entryList;
	}
	
	public List<YouTubeFeedEntry> getVideos(String queryStr) {
		try {
			YouTubeQuery query = new YouTubeQuery(new URL(YOUTUBE_FEEDS_URL));
			query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
			query.setFullTextQuery(queryStr);
			query.setMaxResults(MAX_RESULTS);
			
			VideoFeed vf = service.query(query, VideoFeed.class);
			List<VideoEntry> videos = vf.getEntries();
			
			return convertToFeedEntries(videos);
		} catch (Exception e) { 
			System.out.println("[YouTubeFeedRetriver] Error: " + e.toString());
		}
		return null;
	}
}